from rest_framework import serializers
from .models import (
    CourseCategory,
    CourseCollection,
    CourseVideo,
    CourseComment,
    CourseLike,
    CourseOrder
)
from django.contrib.auth import get_user_model

User = get_user_model()

class UserSimpleSerializer(serializers.ModelSerializer):
    """用于展示用户基础信息"""
    class Meta:
        model = User
        fields = ['id', 'username', 'avatar']  # 确保 User 模型有 avatar 字段


class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseCategory
        fields = ['id', 'name']


class CourseVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseVideo
        fields = ['id', 'title', 'video_file', 'order', 'uploaded_at']


class CourseCommentSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)

    class Meta:
        model = CourseComment
        fields = ['id', 'user', 'content', 'created_at']


class CourseCollectionListSerializer(serializers.ModelSerializer):
    """用于列表展示合集信息"""
    teacher = UserSimpleSerializer(read_only=True)
    like_count = serializers.IntegerField(source='likes.count', read_only=True)

    class Meta:
        model = CourseCollection
        fields = ['id', 'title', 'cover_image', 'price', 'is_free', 'teacher', 'like_count', 'created_at']


class CourseCollectionDetailSerializer(serializers.ModelSerializer):
    """合集详情展示，包括视频、评论、点赞等"""
    teacher = UserSimpleSerializer(read_only=True)
    category = CourseCategorySerializer(read_only=True)
    videos = CourseVideoSerializer(many=True, read_only=True)
    comments = CourseCommentSerializer(many=True, read_only=True)
    like_count = serializers.IntegerField(source='likes.count', read_only=True)

    class Meta:
        model = CourseCollection
        fields = [
            'id', 'title', 'description', 'cover_image', 'is_free', 'price',
            'teacher', 'category', 'created_at', 'videos', 'comments', 'like_count'
        ]


class CourseCollectionCreateSerializer(serializers.ModelSerializer):
    """用于创建新的合集（上传课程）"""
    class Meta:
        model = CourseCollection
        fields = ['title', 'description', 'category', 'cover_image', 'is_free', 'price']


class CourseOrderSerializer(serializers.ModelSerializer):
    course_collection = CourseCollectionListSerializer(read_only=True)

    class Meta:
        model = CourseOrder
        fields = ['id', 'course_collection', 'paid', 'order_time']
